<template>
  <view class="home-container">
    <nav-bar
      :bgColor="themeColor"
      :supportWhiteBlack="false"
      :rightCustomerStyle="{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-end',
      }"
    >
      <view slot="navLeft" class="pubUserInfoName title-hidden-one">
        {{ pubUserInfo.pubDomainShopVo.shopName || "哈哈生活圈" }}
      </view>
      <view slot="navContent" class="navContent">
        <div class="share" @click="handleShowShare">
          <u-icon
            name="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/pub_merchant_wxapp/home_share.png"
            size="18"
          />
        </div>
      </view>
    </nav-bar>
    <view class="container" id="guide-container">
      <official-account
        :guide_option="guide_option"
        v-if="isShowOfficialAccount"
      />
      <data-board />
      <order-grid
        :attribute="orderGridAttribute"
        :guide_option="guide_option"
      />
      <classify-grid
        :guide_option="guide_option"
        :attribute="baseGridAttribute"
      />
      <classify-grid
        :guide_option="guide_option"
        :attribute="shopManagerGridAttribute"
      />
    </view>
    <view class="blank-box"></view>
    <!--    <low-code-page-->
    <!--      ref="lcpRef"-->
    <!--      hideNavbar-->
    <!--      v-if="pageData"-->
    <!--      :pageJson="pageData"-->
    <!--    />-->
    <!--    <button @click="jumpPages('orderList')">订单列表</button>-->
    <!--    <button @click="jumpPages('productList')">商品列表</button>-->
    <!--    <button @click="jumpPages('productClass')">商品分类</button>-->
    <!--    <button @click="jumpPages('deskManage')">桌码管理</button>-->
    <mask-guide ref="maskGuide" :lastIndex="lastIndex"> </mask-guide>
    <cus-tab-bar />
    <share-modal :showTitle="false" :visible.sync="isShowShare" />
  </view>
</template>

<script>
import {
  getWxAppPageQrcode,
  getWxConfig,
  isSubscribe,
  login,
} from "@/service/api/sp-common";
import { appSetStorage } from "@/utils/storage";
import officialAccount from "@/components/pageComponents/sp-home/official-account";
import shareModal from "@/components/pageComponents/sp-home/share-modal";
import dataBoard from "@/components/pageComponents/sp-home/databoard";
import maskGuide from "@/components/baseComponents/mask-guide";
import orderGrid from "@/components/pageComponents/sp-home/orderGrid";
import classifyGrid from "@/components/pageComponents/sp-home/classify-grid";
import { PUB_BUSINESS_WX_CONFIG_STORAGE_KEY } from "@/const/application/config";
import { GRID_OPTION, handleSolveClassifyGrid } from "@/pages/home/const";
// import { guide_option } from "@/pages/home/const/mask-guide";
import { isFirstLogin } from "@/service/api/sp-common/user";
import {
  PUB_BUSINESS_MA_APPID,
  PUB_BUSINESS_MA_LOGIN_PASSWORD,
  PUB_BUSINESS_MA_LOGIN_PHONE,
  PUB_IS_FIRST_LOGIN,
  PUB_FIRST_LOGIN_PUBUSERINFO,
} from "@/const/application/auth";
import { mapState } from "vuex";
import { orderList } from "@/service/api/sp-order";
import { ORDER_STATUS } from "@/pages/sp-order/const/order";
import { appRemoveStorage } from "../../utils/storage";

export default {
  components: {
    classifyGrid,
    officialAccount,
    dataBoard,
    maskGuide,
    orderGrid,
    shareModal,
  },
  data() {
    return {
      isShowOfficialAccount: true,
      isShowShare: false,
      guide_option: {},
      orderGridAttribute: {
        type: "imageAndText",
        col: 4,
        list: GRID_OPTION,
      },
      baseGridAttribute: {
        type: "imageAndText",
        col: 4,
        list: handleSolveClassifyGrid(),
      },
      shopManagerGridAttribute: {
        type: "imageAndText",
        col: 4,
        list: handleSolveClassifyGrid(),
      },
      qrcode: "",
      options: null,
    };
  },
  onShareAppMessage(res) {
    let mpPath = "";
    if (
      this.pubUserInfo?.pubDomainShopVo.pubTag === 1 &&
      this.pubUserInfo?.pubDomainShopVo?.shopType === 3
    ) {
      mpPath = `pages/sp-store/pages/business-district-index-page/index?shopId=${this.pubUserInfo.pubDomainShopVo.id}`;
    } else {
      mpPath = `pages/sp-store/pages/shop-index/index?shopId=${this.pubUserInfo.pubDomainShopVo.id}`;
    }
    return {
      title: this.pubUserInfo.name,
      path: "",
      imageUrl: this.qrcode,
      mpId: process.env.VUE_APP_PUB_USER_WX_APP_ID,
      mpPath,
      type: process.env.NODE_ENV === "production" ? 0 : 2,
    };
  },
  computed: {
    lastIndex({ guide_option }) {
      let index = 0;
      for (const argumentsKey in guide_option) {
        index += 1;
      }
      return index;
    },
    ...mapState("sp-common/auth", ["token"]),
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
  },
  watch: {
    token: {
      handler(val) {
        if (val) {
          this.$store.dispatch("sp-product/index/setCalssifyList");
          this.$store.dispatch("sp-product/index/setShopList");
          this.$nextTick(() => {
            this.fetchOrderList();
            this.getQRCode();
            this.innitMaskGuideConfig();
          });
        }
      },
      immediate: true,
    },
    pubUserInfo: {
      handler(val) {
        if (this.options?.scope && val) {
          //从app来登录的
          appSetStorage(PUB_FIRST_LOGIN_PUBUSERINFO, val);
        }
      },
      deep: true,
    },
  },
  created() {
    this.innitConfig();
  },
  onShow() {
    if (this.token) {
      this.fetchOrderList();
    }
  },
  onLoad(options) {
    console.log("首页参数", options);
    this.options = options;
    uni.showShareMenu({
      title: "哈哈生活圈·商户端",
    });
    if (options?.scope) {
      //从app来登录的
      console.log("从app来登录的", options);
      appRemoveStorage(PUB_FIRST_LOGIN_PUBUSERINFO);
      this.$nextTick(() => {
        this.handleFromAppLogin(options);
      });
    }
    uni.getSetting({
      success(res) {
        if (!res.authSetting["scope.camera"]) {
          uni.authorize({
            scope: "scope.camera",
          });
        }
      },
    });
  },
  methods: {
    handleFromAppLogin(e) {
      const chooseBusinessInfo = e;
      login({
        phone: chooseBusinessInfo.phone,
        password: chooseBusinessInfo.password,
        businessId: "",
        userId: chooseBusinessInfo.userId,
        scope: "pubDomainBusinessApp",
        pubDomainBusinessId: chooseBusinessInfo.pubDomainBusinessId,
      })
        .then((login_res) => {
          // console.log("从app来登录的");
          if (login_res) {
            appSetStorage(
              PUB_BUSINESS_MA_LOGIN_PHONE,
              chooseBusinessInfo.phone
            );
            appSetStorage(
              PUB_BUSINESS_MA_LOGIN_PASSWORD,
              chooseBusinessInfo.password
            );

            this.$store.dispatch(
              "sp-common/auth/setUserInfoAction",
              chooseBusinessInfo
            );
            this.$store.dispatch("sp-common/auth/setTokenAction", login_res);
          }
        })
        .catch((e) => {
          uni.showToast({
            title: e?.msg,
            icon: "none",
          });
        });
    },
    async innitConfig() {
      this.baseGridAttribute.list = handleSolveClassifyGrid({}, "base");
      this.shopManagerGridAttribute.list = handleSolveClassifyGrid(
        {},
        "shopManager"
      );
      const res = await getWxConfig({ scope: 1 });
      appSetStorage(PUB_BUSINESS_WX_CONFIG_STORAGE_KEY, res);
    },
    async getQRCode() {
      let mpPath = "";
      if (
        this.pubUserInfo?.pubDomainShopVo?.pubTag === 1 &&
        this.pubUserInfo?.pubDomainShopVo?.shopType === 3
      ) {
        mpPath = `pages/sp-store/pages/business-district-index-page/index?shopId=${this.pubUserInfo.pubDomainShopVo.id}`;
      } else {
        mpPath = `pages/sp-store/pages/shop-index/index?shopId=${this.pubUserInfo.pubDomainShopVo.id}`;
      }
      const res = await getWxAppPageQrcode({
        appId: process.env.VUE_APP_PUB_USER_WX_APP_ID,
        page: mpPath,
        type: process.env.NODE_ENV === "production" ? 0 : 2,
      });
      if (res) {
        this.qrcode = res;
      }
    },
    innitMaskGuideConfig() {
      uni.login({
        provider: "weixin", //使用微信登录
        success: async (loginRes) => {
          if (loginRes.errMsg === "login:ok") {
            const res = await isSubscribe({
              code: loginRes.code,
              appId: process.env.VUE_APP_WX_APP_ID,
            });
            if (res) {
              const { subscribe, maOpenId } = res;
              appSetStorage(PUB_BUSINESS_MA_APPID, maOpenId);
              this.isShowOfficialAccount = !subscribe;
              let originOptions = {};
              const official_account_guide = {
                from: "来自首页关注组件的蒙层提示",
                // id: "guide_0",
                dataGuideText: "先关注公众号，有订单第一时间提醒",
              };
              if (!subscribe) {
                originOptions.official_account_guide = official_account_guide;
              }
              if (this.pubUserInfo.mainShopStatus) {
                originOptions = {
                  ...originOptions,
                  storeList_guide: {
                    from: "首页门店管理提示",
                    // id: "guide_1",
                    dataGuideText: "完善门店资料，启用门店在用户小程序展示",
                  },
                  productList_guide: {
                    from: "首页基本工具商品列表提示",
                    // id: "guide_2",
                    dataGuideText:
                      "添加商品，上架商品在用户小程序显示，用户可下单购买",
                  },
                  order_grid_guide: {
                    from: "首页订单状态宫格",
                    // id: "guide_3",
                    dataGuideText: "查看/处理订单",
                  },
                };
              } else {
                originOptions = {
                  ...originOptions,
                  productList_guide: {
                    from: "首页基本工具商品列表提示",
                    // id: "guide_2",
                    dataGuideText: "上架商品在用户小程序显示，用户可下单购买",
                  },
                  order_grid_guide: {
                    from: "首页订单状态宫格",
                    // id: "guide_3",
                    dataGuideText: "查看/处理订单",
                  },
                };
              }
              this.guide_option = Object.assign({}, originOptions);
              this.$nextTick(() => {
                const guide_option = this.guide_option;
                let index = 0;
                for (const argumentsKey in guide_option) {
                  guide_option[argumentsKey].id = `guide_${index}`;
                  index += 1;
                }
                this.baseGridAttribute.list = handleSolveClassifyGrid(
                  guide_option,
                  "base"
                );
                this.shopManagerGridAttribute.list = handleSolveClassifyGrid(
                  guide_option,
                  "shopManager"
                );
                if (!this.pubUserInfo.mainShopStatus) {
                  //分店不需要门店管理
                  this.shopManagerGridAttribute.list.map((item) => {
                    item.list = item.list.filter((v) => v.text !== "门店管理");
                  });
                  //分店不需要上商品分类
                  this.baseGridAttribute.list.map((item) => {
                    item.list = item.list.filter((v) => v.text !== "商品分类");
                  });
                }
                if (Number(this.pubUserInfo.pubDomainShopVo.industry) > 100) {
                  //<=100属于餐饮，>100属于其他行业了
                  this.shopManagerGridAttribute.list.map((item) => {
                    item.list = item.list.filter((v) => v.text !== "桌码管理");
                  });
                }
                this.$nextTick(() => {
                  this.startMaskGuide();
                });
              });
            }
          }
        },
      });
    },
    async startMaskGuide() {
      const isFirstLoginRes = await isFirstLogin();
      appSetStorage(PUB_IS_FIRST_LOGIN, isFirstLoginRes);
      if (isFirstLoginRes) {
        setTimeout(() => {
          this.$refs.maskGuide.start({
            textStyle: {
              fontSize: "28rpx",
            },
            showNextButton: true,
          });
        }, 200);
      }
    },
    async fetchOrderList() {
      const res = await orderList({
        appFlag: true,
        beginTime: "",
        businessName: "",
        endTime: "",
        memberPhone: "",
        mercNo: "",
        sortWay: 0,
        orderNo: "",
        pageNum: 1,
        pageSize: 10,
        deliveryTypes: [],
        paymentMethod: "",
        pubOrderStatus: ORDER_STATUS.UNDERWAY,
        pubShopId: "",
      });
      this.orderGridAttribute.list.map((item) => {
        if (item.isUseHot && item.orderStatus === ORDER_STATUS.UNDERWAY) {
          item.isShowHot = !!res?.total;
        }
      });
    },
    jumpPages(path) {
      this.$Router.push({
        name: path,
      });
    },
    handleShowShare() {
      if (!this.token) {
        uni.showModal({
          title: "提示",
          content: "暂无登录，请登录",
          confirmColor: this.$theme.themeColor.primary,
          success: (res) => {
            if (res.confirm) {
              uni.redirectTo({
                url: "/pages/sp-common/pages/login/index",
              });
            }
          },
        });
        return;
      }
      this.isShowShare = true;
    },
  },
};
</script>

<style scoped lang="scss">
.home-container {
  background-color: whitesmoke;
  min-height: 100vh;
  overflow: scroll;
}
.navContent {
}
.logo {
  width: 100%;
  height: 800rpx;
}
.pubUserInfoName {
  font-size: 32rpx;
  font-family: PingFang SC;
  font-weight: bold;
  color: #fff;
  width: 450rpx;
}
.blank-box {
  width: 686rpx;
  height: 100rpx;
}
</style>
